package top.mczhengyi.xyblog.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.mczhengyi.xyblog.auth.RequireLogin;
import top.mczhengyi.xyblog.entity.Blog;
import top.mczhengyi.xyblog.entity.Result;
import top.mczhengyi.xyblog.entity.ResultCode;
import top.mczhengyi.xyblog.service.BlogService;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @GetMapping("/{id}")
    public Result getBlogById(@PathVariable("id") Integer id) {
        Blog blog = blogService.getBlogById(id);
        if (blog == null) {
            return Result.fail(ResultCode.NOT_FIND_BLOG);
        }
        return Result.success(blog);
    }

    @GetMapping("")
    public Result getAllBlog(String type) {
        List<Blog> blogs;
        // 能否获取全部博客
        if ("all".equals(type)) {
            blogs = blogService.getAllBlog();
        } else {
            blogs = blogService.getVisibleBlog();
        }
        if (blogs == null) {
            return Result.fail(ResultCode.UNKNOWN_FAIL);
        }
        return Result.success(blogs);
    }

    @PostMapping("")
    @RequireLogin
    public Result saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        Integer op = blogService.saveBlog(blog);
        if (op == 0) {
            return Result.fail(ResultCode.UNKNOWN_FAIL);
        }
        return Result.success();
    }

    @PutMapping("/{id}")
    @RequireLogin
    public Result update(Blog blog, @PathVariable("id") Integer id) {
        blog.setId(id);
        Integer op = blogService.updateBlog(blog);
        if (op == 0) {
            return Result.fail(ResultCode.UNKNOWN_FAIL);
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @RequireLogin
    public Result delete(@PathVariable("id") Integer id) {
        Integer res = blogService.delete(id);
        if (res == 0) {
            return Result.fail(ResultCode.UNKNOWN_FAIL);
        }
        return Result.success();
    }
}
